/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package trabalho3;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

/**
 *
 * @author mateus
 */
public class OportunidadeJpaController<T> implements Serializable {

    private Query query;
    private List<T> list;
    private EntityManager em;

    public OportunidadeJpaController(EntityManagerFactory emf) {
        this.em = emf.createEntityManager();
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    
    public void create(T tipo) {
        em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            em.persist(tipo);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }


    public void destroy(Class<T> tipo,Long id){
        em = getEntityManager();
        em.getTransaction().begin();
        T opor = em.getReference(tipo, id);
        em.remove(opor);
        em.getTransaction().commit();
        
    }

    public List<T> findOportunidadeEntities(String tipo) {
        query = em.createQuery("SELECT o FROM " + tipo + " o");
        list = query.getResultList();
        Collection data = query.getResultList();
        for (Object entity : data) {
            em.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        return list;

    }

    public int getRowCount(String tipo) {
        query = em.createQuery("SELECT count(o) FROM " + tipo + " o");
        long t = (long) query.getSingleResult();
        int a = (int) t;
        return a;
    }

    public void edit(T tipo) {
        em = getEntityManager();
        em.getTransaction().begin();
        tipo = em.merge(tipo);
        em.getTransaction().commit();
        em.close();

    }

    
    
     public List<T>  procuratitulo(String tipo,String existe) {
        query = em.createQuery("SELECT o FROM " + tipo + " o WHERE o.titulo LIKE '%"+existe+"%' OR o.descricao LIKE '%"+existe+"%'");
         list = query.getResultList();
        Collection data = query.getResultList();
        for (Object entity : data) {
            em.refresh(entity);
        }
        list.clear();
        list.addAll(data);       
        return list;
    }
     
    
    
     
}
